import { Context } from "koa";
import SysUserServer from "../../server/Sys/SysUserServer";
import response from "../../util/response";
import UserServer from "../../server/UserServer";
import md5 from "md5";
/*
 * @Author: fishroom
 * @Date: 2022-10-14 10:24:27
 * @LastEditTime: 2023-01-04 17:54:34
 * @FilePath: \koa\app\controller\Sys\SysUserController.ts
 */
class SysUserController {
  async getUserList(ctx: Context) {
    let params = ctx.query;
    // 初始化页码
    let limit = 10,
      page = 1;
    if (params.limit) {
      limit = Number(params.limit);
      delete params.limit;
    }
    if (params.page) {
      page = Number(params.page);
      delete params.page;
    }
    // 去除空参数
    for (let key in params) {
      if (!params[key]) {
        delete params[key];
      }
    }
    // 去除时间
    delete params["t"];
    const { rows, count } = await SysUserServer.getUserList(limit, (page - 1) * limit, params);
    return response.CxtSuccess(ctx, { page: rows, count, limit, currPage: page });
  }
  async updateUserById(ctx: Context) {
    let obj = ctx.request.body;
    if (ctx.$user.role_id >= 2 || ctx.$user.role_id < obj.role_id) {
    return  response.CxtError(ctx, "添加失败,权限不足");
    }
    try {
      await SysUserServer.updateUserById(obj);
      response.CxtSuccess(ctx, { msg: "修改成功" });
    } catch (error) {
      response.CxtError(ctx, "失败", { error });
    }
  }
  async selectUserById(ctx: Context) {
    try {
      let user_id = ctx.query["id"];
      let { rows } = await SysUserServer.getUserList(1, 0, { user_id: Number(user_id) });
      response.CxtSuccess(ctx, rows[0]);
    } catch (error) {
      response.CxtError(ctx, "失败", { error });
    }
  }
  async addUser(ctx: Context) {
    try {
      let newUser = ctx.request.body;
      console.log(ctx.$user.role_id, newUser.role_id);
      
      if (ctx.$user.role_id >= 2 || ctx.$user.role_id < newUser.role_id) {
      return  response.CxtError(ctx, "添加失败,权限不足");
      }
      newUser.password = md5(newUser.password as string);
      const data = await UserServer.addUser(newUser);
      response.CxtSuccess(ctx, data);
    } catch (error) {
      response.CxtError(ctx, "添加失败", { error });
    }
  }
  async deleteUser(ctx: Context) {
    try {
      let user_ids = ctx.request.body;
      let msg = await SysUserServer.deleteUserById(user_ids);
      response.CxtSuccess(ctx, { msg });
    } catch (error) {
      response.CxtError(ctx, "错误");
    }
  }
}
export default new SysUserController();
